package com.gitee.huxing.course.conc.conc01.sync;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.cono01.sync
 * @ClassName: Counter
 * @Author: huxing
 * @DateTime: 2021-08-20 上午11:19
 */
public class Counter {

    private int sum = 0;

    private Object lock = new Object();

    public void incr(){
        synchronized (lock){
            sum = sum + 1;
        }
    }

    public int getSum(){
        return sum;
    }

    public static void main(String[] args) throws InterruptedException{

        int loop = 10_1000;

        Counter counter = new Counter();
        for (int i= 0; i <loop; i++){
            counter.incr();
        }
        System.out.println("single thread: " + counter.getSum());

        final Counter counter2 = new Counter();
        Thread t1 = new Thread(()->{
            for (int i =0; i< loop/2; i++){
                counter2.incr();
            }
        }, "t1");
        Thread t2 = new Thread(()->{
            for (int i =0; i< loop/2; i++){
                counter2.incr();
            }
        }, "t2");
        t1.start();
        t2.start();
        Thread.sleep(1000);
        System.out.println("multiple threads: " + counter2.getSum());
    }
}
